<template>
  <div class="product-management">
    <div class="header">
      <h2>商品管理</h2>
      <button @click="$router.push('/dashboard')" class="back-btn">返回首页</button>
    </div>
    
    <!-- 添加商品表单 -->
    <div class="add-product-form">
      <input v-model="newProduct.name" placeholder="商品名称" />
      <input v-model="newProduct.price" type="number" placeholder="价格" />
      <input v-model="newProduct.stock" type="number" placeholder="库存" />
      <button @click="addProduct" :disabled="!isValidProduct">添加商品</button>
    </div>

    <!-- 商品列表 -->
    <table class="product-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>名称</th>
          <th>价格</th>
          <th>库存</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="product in products" :key="product.id">
          <td>{{ product.id }}</td>
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
          <td>{{ product.stock }}</td>
          <td>
            <button @click="editProduct(product)">编辑</button>
            <button @click="deleteProduct(product.id)" class="delete-btn">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 编辑商品对话框 -->
    <div v-if="showEditDialog" class="edit-dialog">
      <div class="edit-dialog-content">
        <h3>编辑商品</h3>
        <div class="form-group">
          <label>商品名称：</label>
          <input v-model="editingProduct.name" />
        </div>
        <div class="form-group">
          <label>价格：</label>
          <input v-model="editingProduct.price" type="number" />
        </div>
        <div class="form-group">
          <label>库存：</label>
          <input v-model="editingProduct.stock" type="number" />
        </div>
        <div class="dialog-buttons">
          <button @click="updateProduct">保存</button>
          <button @click="showEditDialog = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ProductManagement',
  data() {
    return {
      products: [],
      newProduct: {
        name: '',
        price: '',
        stock: ''
      },
      showEditDialog: false,
      editingProduct: null
    }
  },
  computed: {
    isValidProduct() {
      return this.newProduct.name && this.newProduct.price && this.newProduct.stock
    }
  },
  created() {
    this.fetchProducts()
  },
  methods: {
    async fetchProducts() {
      try {
        const response = await axios.get('/api/products', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.products = response.data
      } catch (error) {
        console.error('获取商品列表失败:', error)
        alert('获取商品列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async addProduct() {
      if (!this.isValidProduct) {
        alert('请填写完整的商品信息')
        return
      }

      // 验证价格和库存是否为有效数字
      const price = parseFloat(this.newProduct.price)
      const stock = parseInt(this.newProduct.stock)

      if (isNaN(price) || price <= 0) {
        alert('请输入有效的价格')
        return
      }
      if (isNaN(stock) || stock < 0) {
        alert('请输入有效的库存数量')
        return
      }

      try {
        const response = await axios.post('/api/products', {
          name: this.newProduct.name,
          price: price,
          stock: stock
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.status === 201) {
          this.fetchProducts()
          this.newProduct = { name: '', price: '', stock: '' }
          alert('添加商品成功')
        }
      } catch (error) {
        console.error('添加商品失败:', error)
        const errorMessage = error.response?.data?.message || '未知错误'
        alert(`添加商品失败：${errorMessage}`)
      }
    },
    async deleteProduct(id) {
      if (!confirm('确定要删除这个商品吗？')) {
        return
      }
      try {
        await axios.delete(`/api/products/${id}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchProducts()
        alert('删除商品成功')
      } catch (error) {
        console.error('删除商品失败:', error)
        alert('删除商品失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    editProduct(product) {
      this.editingProduct = { ...product }
      this.showEditDialog = true
    },
    async updateProduct() {
      try {
        await axios.put(`/api/products/${this.editingProduct.id}`, this.editingProduct, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchProducts()
        this.showEditDialog = false
        alert('更新商品成功')
      } catch (error) {
        console.error('更新商品失败:', error)
        alert('更新商品失败：' + (error.response?.data?.message || '未知错误'))
      }
    }
  }
}
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-product-form {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
}

.product-table th,
.product-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.product-table th {
  background-color: #f5f5f5;
}

button {
  margin: 0 5px;
  padding: 5px 10px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.delete-btn {
  background-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #f78989;
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #909399;
}

.cancel-btn:hover {
  background-color: #a6a9ad;
}
</style> 